package com.boot;

/**
 * 缓存系统
 */

import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Function;

public class GlobalCache  {
    private static final ConcurrentHashMap<String, Object> CACHE = new ConcurrentHashMap<>();
    public static void main(String[] args) {
        // 模拟多线程环境
        for (int i = 0; i < 10; i++) {
            new Thread(() -> {
                String key = "user_" + Thread.currentThread().getId();
                // 如果不存在则计算并放入缓存
                Object value = computeIfAbsent(key, k -> {
                    System.out.println("计算值 for " + k);
                    return k + "_value";
                });
                System.out.println(key + " => " + value);
            }).start();
        }
    }
    // 线程安全的缓存获取
    public static Object get(String key) {
        return CACHE.get(key);
    }
    // 线程安全的缓存放入（如果不存在）
    public static void putIfAbsent(String key, Object value) {
        CACHE.putIfAbsent(key, value);
    }

    // 线程安全的缓存计算（如果不存在则计算）
    public static Object computeIfAbsent(String key, Function<String, Object> function) {
        return CACHE.computeIfAbsent(key, function);
    }




}
